// ActionHelper-负责数据处理，笔记数据的整理
import DataHelper from "@/store/DataHelper";
import ItemDetail from "@/model/ItemDetail";

class ActionHelper {
    // 1. 负责数据处理
    dataHelper: DataHelper = new DataHelper("memoData", "id");
    // 1.1 笔记数组其实就是Array<Object,Object...>
    memoList!: Array<ItemDetail>;

    constructor() {
        this.memoList = this.readData();
    }

    // 读取本地数据，返回ItemData---------------------------------------------
    readData(): Array<ItemDetail> {
        /**
         * 从loaclostorage拿到的json数据,类数组
         * {
         *    {'id':1,'title':'hey'},
         *    {'id':1,'title':'hey'}
         *  }
         */
        let arrObj = this.dataHelper.readData();
        let arrItem = arrObj.map((e: any) => {
            let item: ItemDetail = new ItemDetail();
            item.id = e.id;
            item.categoryId = e.categoryId;
            item.title = e.title;
            item.content = e.content;
            item.createTime = e.createTime;
            // 我觉得这里不需要return
            return item;
        });
        // console.log(arrItem);
        return arrItem;
    }

    getCategoryName(cateId: number): string {
        const arr = ["工作", "生活", "学习"];
        return arr[cateId];
    }

    // 新增笔记，返回添加笔记的id
    add(item: ItemDetail): number {
        item.id = this.dataHelper.addData(item);
        this.memoList.push(item);
        this.dataHelper.saveData(this.memoList);
        return item.id;
    }

    // 修改笔记（这里默认已经将ItemDetail传递过来，只需要查找数据库对应的数据，为对应的字段重新赋值，并保存）
    edit(item: ItemDetail): void {
        let editItem: ItemDetail | undefined = this.memoList.find(
            (e) => e.id == item.id
        );
        if (editItem) {
            editItem.categoryId = item.categoryId;
            editItem.title = item.title;
            editItem.content = item.content;

            this.dataHelper.saveData(this.memoList);
        }
    }

    // 删除笔记
    remove(id: number): void {
        let index: number = this.memoList.findIndex((e) => e.id == id);
        if (index > -1) {
            this.memoList.splice(index, 1);
            this.dataHelper.saveData(this.memoList);
        }
    }
}

export default ActionHelper;
